import os
import sys
import pygame
import pygame.freetype
import logging
from datetime import datetime

# 添加项目根目录到 Python 路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

from dazi_beidanci.src.theme import Theme
from dazi_beidanci.src.views.menu_view import MenuView
from dazi_beidanci.src.views.practice_view import PracticeView
from dazi_beidanci.src.views.study_view import StudyView
from dazi_beidanci.src.views.stats_view import StatsView
from dazi_beidanci.src.views.wordbank_view import WordBankView
from dazi_beidanci.src.word_bank import WordBank
from dazi_beidanci.src.user_profile import UserProfile

def init_directories():
    """初始化必要的目录结构"""
    directories = [
        "data",
        "data/user_data",
        "data/word_banks",
        "assets",
        "assets/sounds",
        "assets/fonts",
        "logs"
    ]
    
    for directory in directories:
        if not os.path.exists(directory):
            os.makedirs(directory)

def init_logging():
    """初始化日志系统"""
    log_file = f"logs/app_{datetime.now().strftime('%Y%m%d')}.log"
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler(log_file, encoding='utf-8'),
            logging.StreamHandler()
        ]
    )

def main():
    # 初始化目录结构
    init_directories()
    
    # 初始化日志系统
    init_logging()
    
    # 初始化 pygame
    pygame.init()
    
    # 初始化音频系统
    pygame.mixer.init()
    
    try:
        # 设置窗口
        width = 1024
        height = 768
        screen = pygame.display.set_mode((width, height))
        pygame.display.set_caption("打字练习")
        
        # 初始化数据目录
        init_directories()
        
        # 初始化主题
        theme = Theme()
        
        # 创建共享的词库实例并初始化
        word_bank = WordBank()
        word_bank.initialize_word_banks()  # 先初始化词库
        
        # 确保词库已加载
        if not word_bank.words:
            current_bank = word_bank.current_bank
            word_bank.load_word_bank(current_bank)
            logging.info(f"加载词库: {current_bank}")
        
        # 初始化用户档案系统
        user_profile = UserProfile(project_root)
        
        # 创建视图
        views = {
            "menu": MenuView(screen, theme, word_bank, user_profile),
            "practice": PracticeView(screen, theme, word_bank, user_profile),
            "study": StudyView(screen, theme, word_bank, user_profile),
            "stats": StatsView(screen, theme, word_bank, user_profile),
            "wordbank": WordBankView(screen, theme, word_bank, user_profile)
        }
        logging.info("所有视图初始化成功")
        
        current_view = "menu"
        running = True
        clock = pygame.time.Clock()
        
        while running:
            # 处理事件
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    continue
                    
                # 处理视图事件
                result = views[current_view].handle_event(event)
                if result == "quit":
                    running = False
                elif result:
                    current_view = result
            
            # 绘制当前视图
            views[current_view].draw()
            pygame.display.flip()
            
            # 控制帧率
            clock.tick(60)
        
    except Exception as e:
        logging.error(f"程序运行时发生错误: {str(e)}")
        raise
    finally:
        pygame.quit()
        logging.info("程序正常退出")

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        logging.error(f"程序异常退出: {str(e)}")
        raise
    finally:
        logging.info("程序正常退出")
        pygame.quit()
